// 工具栏初始化
function initToolbar() {
  // 添加工具栏到页面
  const toolbar = document.createElement("div");
  toolbar.className = "toolbar";
  toolbar.innerHTML = `
        <button class="tool-btn" data-tooltip="选择模板">
            <i class="fas fa-check-square"></i>
        </button>
        <button class="tool-btn" data-tooltip="模板列表">
            <i class="fas fa-list"></i>
        </button>
        <button class="tool-btn" data-tooltip="添加模板">
            <i class="fas fa-plus"></i>
        </button>
        <button class="tool-btn" data-tooltip="编辑模板">
            <i class="fas fa-edit"></i>
        </button>
        <button class="tool-btn" data-tooltip="删除模板">
            <i class="fas fa-trash"></i>
        </button>
        <button class="tool-btn" data-tooltip="导入导出">
            <i class="fas fa-exchange-alt"></i>
        </button>
        <button class="tool-btn" data-tooltip="帮助">
            <i class="fas fa-question-circle"></i>
        </button>
    `;
  document.body.appendChild(toolbar);

  // 添加侧边面板
  const sidePanel = document.createElement("div");
  sidePanel.className = "side-panel";
  sidePanel.innerHTML = `
        <div class="panel-header">
            <h2 class="panel-title">模板管理</h2>
            <button class="close-btn">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="panel-content"></div>
    `;
  document.body.appendChild(sidePanel);

  // 关闭按钮事件
  sidePanel.querySelector(".close-btn").addEventListener("click", () => {
    sidePanel.classList.remove("active");
    // 移除所有工具按钮的激活状态
    document
      .querySelectorAll(".tool-btn")
      .forEach((btn) => btn.classList.remove("active"));
    // 清空面板内容
    panel.querySelector(".panel-content").innerHTML = "";
  });

  // 工具栏按钮点击处理
  document.querySelectorAll(".tool-btn").forEach((btn) => {
    btn.addEventListener("click", function () {
      const tooltip = this.getAttribute("data-tooltip");
      const isActive = this.classList.contains("active");

      // 移除其他按钮的激活状态
      document
        .querySelectorAll(".tool-btn")
        .forEach((b) => b.classList.remove("active"));

      // 如果当前按钮已经是激活状态，则关闭面板
      if (isActive) {
        sidePanel.classList.remove("active");
        sidePanel.querySelector(".panel-content").innerHTML = "";
        return;
      }

      // 激活当前按钮
      this.classList.add("active");

      // 显示对应的面板内容
      switch (tooltip) {
        case "选择模板":
          showTemplateSelect(sidePanel);
          break;
        case "模板列表":
          showTemplateList(sidePanel);
          break;
        case "添加模板":
          showAddTemplate(sidePanel);
          break;
        case "编辑模板":
          showEditTemplate(sidePanel);
          break;
        case "删除模板":
          showDeleteTemplate(sidePanel);
          break;
        case "导入导出":
          showImportExport(sidePanel);
          break;
        case "帮助":
          showHelp(sidePanel);
          break;
      }
    });
  });
}

// 显示模板列表
function showTemplateList(panel) {
  panel.querySelector(".panel-title").textContent = "模板列表";
  panel.querySelector(".panel-content").innerHTML = `
    <div class="template-search">
      <input type="text" placeholder="搜索模板...">
    </div>
    <div class="template-list">
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>模板名称</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>TEST3</td>
            <td>
              <button class="btn-view">查看</button>
            </td>
          </tr>
          <tr>
            <td>2</td>
            <td>TEST_BLOB2</td>
            <td>
              <button class="btn-view">查看</button>
            </td>
          </tr>
          <tr>
            <td>3</td>
            <td>LIS_REPORT44ZH</td>
            <td>
              <button class="btn-view">查看</button>
            </td>
          </tr>
          <tr>
            <td>4</td>
            <td>LIS_REPORT21</td>
            <td>
              <button class="btn-view">查看</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  `;
  panel.classList.add("active");
}

// 显示添加模板界面
function showAddTemplate(panel) {
  panel.querySelector(".panel-title").textContent = "添加模板";
  panel.querySelector(".panel-content").innerHTML = `
    <form class="template-form">
      <div class="form-group">
        <label>模板名称</label>
        <input type="text" placeholder="请输入模板名称">
      </div>
      <div class="form-group">
        <label>模板内容</label>
        <textarea rows="10" placeholder="请输入模板内容"></textarea>
      </div>
      <button type="submit" class="btn-submit">保存</button>
    </form>
  `;
  panel.classList.add("active");
}

// 显示编辑模板界面
function showEditTemplate(panel) {
  panel.querySelector(".panel-title").textContent = "编辑模板";
  panel.querySelector(".panel-content").innerHTML = `
    <div class="template-search">
      <input type="text" placeholder="搜索要编辑的模板...">
    </div>
    <div class="template-list">
      <!-- 模板列表内容 -->
    </div>
  `;
  panel.classList.add("active");
}

// 显示删除模板确认
function showDeleteTemplate(panel) {
  panel.querySelector(".panel-title").textContent = "删除模板";
  panel.querySelector(".panel-content").innerHTML = `
    <div class="template-search">
      <input type="text" placeholder="搜索要删除的模板...">
    </div>
    <div class="template-list">
      <!-- 模板列表内容 -->
    </div>
  `;
  panel.classList.add("active");
}

// 显示导入导出界面
function showImportExport(panel) {
  panel.querySelector(".panel-title").textContent = "导入导出";
  panel.querySelector(".panel-content").innerHTML = `
    <div class="import-export-options">
      <button class="btn-import">导入模板</button>
      <button class="btn-export">导出模板</button>
    </div>
  `;
  panel.classList.add("active");
}

// 显示帮助信息
function showHelp(panel) {
  panel.querySelector(".panel-title").textContent = "帮助";
  panel.querySelector(".panel-content").innerHTML = `
    <div class="help-content">
      <h3>使用说明</h3>
      <p>1. 点击"模板列表"查看所有可用模板</p>
      <p>2. 点击"添加模板"创建新的模板</p>
      <p>3. 点击"编辑模板"修改现有模板</p>
      <p>4. 点击"删除模板"移除不需要的模板</p>
      <p>5. 点击"导入导出"进行模板的导入导出操作</p>
    </div>
  `;
  panel.classList.add("active");
}

// 添加选择模板的功能
function showTemplateSelect(panel) {
  panel.querySelector(".panel-title").textContent = "选择模板";
  panel.querySelector(".panel-content").innerHTML = `
    <div class="template-search">
      <input type="text" placeholder="搜索模板...">
    </div>
    <div class="template-list">
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>模板名称</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>TEST3</td>
            <td>
              <button class="btn-select">选择</button>
              <button class="btn-preview">预览</button>
            </td>
          </tr>
          <tr>
            <td>2</td>
            <td>TEST_BLOB2</td>
            <td>
              <button class="btn-select">选择</button>
              <button class="btn-preview">预览</button>
            </td>
          </tr>
          <tr>
            <td>3</td>
            <td>LIS_REPORT44ZH</td>
            <td>
              <button class="btn-select">选择</button>
              <button class="btn-preview">预览</button>
            </td>
          </tr>
          <tr>
            <td>4</td>
            <td>LIS_REPORT21</td>
            <td>
              <button class="btn-select">选择</button>
              <button class="btn-preview">预览</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  `;

  // 添加选择和预览按钮的事件处理
  panel.querySelectorAll(".btn-select").forEach((btn) => {
    btn.addEventListener("click", function () {
      const templateName =
        this.closest("tr").querySelector("td:nth-child(2)").textContent;
      useTemplate(templateName);
      panel.classList.remove("active");
    });
  });

  panel.querySelectorAll(".btn-preview").forEach((btn) => {
    btn.addEventListener("click", function () {
      const templateName =
        this.closest("tr").querySelector("td:nth-child(2)").textContent;
      previewTemplate(templateName);
    });
  });

  panel.classList.add("active");
}

// 使用模板的功能
function useTemplate(templateName) {
  console.log(`使用模板: ${templateName}`);
  // TODO: 实现模板使用逻辑
}

// 预览模板的功能
function previewTemplate(templateName) {
  console.log(`预览模板: ${templateName}`);
  // TODO: 实现模板预览逻辑
}

// 添加构造提示词的函数
function constructPrompt() {
  const department = document.querySelector('select[name="department"]').value;
  const requiredFields = document.querySelector(
    'textarea[name="requiredFields"]'
  ).value;
  const linkFields = document.querySelector('input[name="linkFields"]');
  const linkFieldsEnabled = document.querySelector("#linkFields").checked;

  if (!requiredFields.trim()) {
    // 如果必填字段为空，显示提示
    alert("请输入需求数据字段");
    return;
  }

  let prompt = "";

  // 构造提示词
  if (department) {
    prompt += `在${department}范围内，`;
  }

  prompt += `查找包含${requiredFields}的数据`;

  if (linkFieldsEnabled && linkFields.value) {
    prompt += `，可通过${linkFields.value}关联`;
  }

  // 获取搜索输入框并设置内容
  const searchInput = document.querySelector(".search-input");
  if (searchInput) {
    searchInput.value = prompt;
    // 添加输入框动画效果
    searchInput.classList.add("highlight");
    setTimeout(() => searchInput.classList.remove("highlight"), 300);
  }
}

// 导出初始化函数
window.initToolbar = initToolbar;

// 显示搜索示例的函数
function showSearchExamples(btn) {
  const popup = btn
    .closest(".keyword-search")
    .querySelector(".search-examples-popup");
  const examples = popup.querySelector(".search-examples");

  // 切换按钮和弹出层状态
  btn.classList.toggle("active");
  popup.classList.toggle("active");

  // 如果是显示状态，则加载示例内容
  if (popup.classList.contains("active")) {
    examples.innerHTML = `
            <div class="example-card" onclick="useExample(this)">
                <h3 class="example-title">场景一：数据分析</h3>
                <p class="example-text">帮我分析近三个月的销售数据，重点关注销售趋势和异常波动</p>
            </div>
            <div class="example-card" onclick="useExample(this)">
                <h3 class="example-title">场景二：数据查询</h3>
                <p class="example-text">查找所有包含客户年龄、消费金额的数据表</p>
            </div>
            <div class="example-card" onclick="useExample(this)">
                <h3 class="example-title">场景三：数据关联</h3>
                <p class="example-text">通过身份证号关联用户基础信息和消费记录</p>
            </div>
            <div class="example-card" onclick="useExample(this)">
                <h3 class="example-title">场景四：数据统计</h3>
                <p class="example-text">统计各部门数据资源数量和使用频率</p>
            </div>
        `;
  }

  // 添加点击外部关闭功能
  document.addEventListener("click", function closePopup(e) {
    if (!popup.contains(e.target) && !btn.contains(e.target)) {
      popup.classList.remove("active");
      btn.classList.remove("active");
      document.removeEventListener("click", closePopup);
    }
  });
}

// 使用示例的函数
function useExample(card) {
  const text = card.querySelector(".example-text").textContent;
  const searchInput = document.querySelector(".search-input");
  const popup = card.closest(".search-examples-popup");
  const btn = document.querySelector(".example-btn");

  // 设置搜索框内容
  searchInput.value = text;

  // 添加输入框动画效果
  searchInput.classList.add("highlight");
  setTimeout(() => searchInput.classList.remove("highlight"), 300);

  // 关闭弹出层
  popup.classList.remove("active");
  btn.classList.remove("active");
}
